/**
 * 将form表单序列化成key:value形式
 */
jQuery.fn.extend({
	serializeArrayToParam: function() {
		var v = {};
		var o = this.serializeArray();
		for (var i in o) {
			if(o[i].value) {
				if (typeof (v[o[i].name]) == 'undefined') {
					v[o[i].name] = o[i].value;
				} else if(v[o[i].name] instanceof Array) {
					v[o[i].name].push(o[i].value);
				} else {
					var t = v[o[i].name];
					v[o[i].name] = [];
					v[o[i].name].push(t);
					v[o[i].name].push(o[i].value);
				}
			}
		}
		for(var i in v) {
			var ss = v[i];
			if(ss instanceof Array) {
				v[i] = ss.join(",");
			}
		}
		return v;
  },serializeArrayToParamStr: function() {
	  //去除空值参数
	  var v = [];
	  var o = this.serializeArray();
	  for (var i in o) {
		  var val = o[i].value;	
		  if(val) {
			v.push(o[i].name);
			v.push("=");
			v.push(val);
		  }
	  }	
	  return v.join("&");
  },insert:function(value) {
	    value=$.extend({ "text":"[]" },value); 
		var dthis = $(this)[0]; //将jQuery对象转换为DOM元素 
		//IE下 
		if(document.selection){ 
			$(dthis).focus(); //输入元素textara获取焦点 
			var fus = document.selection.createRange();//获取光标位置 
			fus.text = value.text; //在光标位置插入值 
			$(dthis).focus(); ///输入元素textara获取焦点 
		} //火狐，google下标准 
		else if(dthis.selectionStart || dthis.selectionStart == '0'){ 
			var start = dthis.selectionStart; //获取焦点前坐标 
			var end =dthis.selectionEnd; //获取焦点后坐标 
			//以下这句，应该是在焦点之前，和焦点之后的位置，中间插入我们传入的值 .然后把这个得到的新值，赋给文本框 
			dthis.value = dthis.value.substring(0, start) + value.text + dthis.value.substring(end, dthis.value.length); 
			$(dthis).focus();
		} 
		//在输入元素textara没有定位光标的情况 
		else{ 
			this.val(this.val() + value.text); this.focus();
		}
		return $(this); 
  }
});

function fnDoReLogin() {
	setTimeout(function() {
		if(window.top.doLogin) {
			window.top.doLogin();
		}
	} , 2000);
}

/**
 * 封装ajax方法，作统一异常错误处理
 * @param options
 */
function fnFormAjaxWithJson(options, notShowProgress){
	//默认显示进度条，当notShowProgress为true时，不显示
	notShowProgress = notShowProgress || false;
	var tmpFun = options.success;
	var callBackFun = function(data){
		if(!notShowProgress) {
			//$.messager.progress('close');
			$(document.body).unmask();
		}
		if(typeof tmpFun==='function'&&tmpFun){
			if(data) {
				if(data.flag=="1" || data.rows || $.isArray(data)) {
					tmpFun(data);
				} else if(data.flag=="3") {
					$.messager.alert($.jwpf.system.alertinfo.errorTitle, data.msg ,'error');
					fnDoReLogin();
				} else {
					$.messager.alert($.jwpf.system.alertinfo.errorTitle, data.msg ,'error');
				}
			}
		}
	};
	options.success = undefined;
	options = $.extend({
		url: false,
		type : 'post',
		dataType : 'json',
		success:callBackFun,
		beforeSend:function(xhr) {
			if(!notShowProgress) {
				//$.messager.progress({text:$.jwpf.system.alertinfo.attachList,interval:20});
				$(document.body).mask("Please Waiting...");
			}
		},
		error:function(xhr, ts, errorThrown) {
			if(!notShowProgress) {
				//$.messager.progress('close');
				$(document.body).unmask();
			}
			$.messager.alert($.jwpf.system.alertinfo.errorTitle,$.jwpf.system.alertinfo.errorInfo,'error');
		},
		complete: function (XMLHttpRequest, textStatus) {
			//$.messager.progress('close');
		}
		},options);
	$.ajax(options);
}

/**
 * EasyUI form提交方法
 * @param formId
 * @param options
 */
function fnEasyUIFormWithJson(formId, options){
	var tmpFun = options.success;
	var callBackFun = function(result){
		if(typeof tmpFun==='function'&&tmpFun){
			if(result) {
				var data = $.parseJSON(result);
				if(data.flag=="1") {
					tmpFun(data);
				} else if(data.flag=="3") {
					$.messager.alert($.jwpf.system.alertinfo.errorTitle, data.msg ,'error');
					fnDoReLogin();
				} else {
					$.messager.alert($.jwpf.system.alertinfo.errorTitle, data.msg ,'error');
				}
			}
		}
	};
	options.success = undefined;
	options = $.extend({
		onSubmit: function(){  
			return $(this).form('validate');
	    },
		success:callBackFun
		},options);
	$("#" + formId).form("submit", options);
}

/**
 * 初始化表单，预提交处理，form提交必须有submit类型按钮触发
 * @param formId 表单ID
 * @param options 可选项，参考$.ajax之options
 */
function fnAjaxFormWithJson(formId, options){
	var tmpFun = options.success;
	var callBackFun = function(data){
		if(typeof tmpFun==='function'&&tmpFun){
			if(data) {
				if(data.flag=="1") {
					tmpFun(data);
				} else {
					$.messager.alert($.jwpf.system.alertinfo.errorTitle, data.msg ,'error');
				}
			}
		}
	};
	options.success = undefined;
	options = $.extend({
		type : 'post',
		dataType : 'json',
		success:callBackFun
		},options);
	$("#" + formId).ajaxForm(options);
}

/**
 * 立即触发ajax表单提交事件，可以加到按钮点击事件中触发
 * @param formId 表单ID
 * @param options 可选项，参考$.ajax之options
 */
function fnAjaxSubmitWithJson(formId, options){
	var tmpFun = options.success;
	var callBackFun = function(data){
		//$.messager.progress('close');
		$(document.body).unmask();
		if(typeof tmpFun==='function'&&tmpFun){
			if(data) {
				if(data.flag=="1") {
					tmpFun(data);
				} else if(data.flag=="3") {
					$.messager.alert($.jwpf.system.alertinfo.errorTitle, data.msg ,'error');
					fnDoReLogin();
				} else {
					$.messager.alert($.jwpf.system.alertinfo.errorTitle, data.msg ,'error');
				}
			}
		}
	};
	options.success = undefined;
	options = $.extend({
		type : 'post',
		dataType : 'json',
		beforeSubmit: function(formData, jqForm, options) {
			return $("#" + formId).form('validate');
		},
		beforeSend:function(xhr) {
			//$.messager.progress({text:'$.jwpf.system.alertinfo.attachList',interval:20});
			$(document.body).mask("Please Waiting...");
		},
		error:function(xhr, ts, errorThrown) {
			//$.messager.progress('close');
			$(document.body).unmask();
			$.messager.alert($.jwpf.system.alertinfo.errorTitle, $.jwpf.system.alertinfo.errorInfo,'error');
		},
		success:callBackFun
		},options);
	$("#" + formId).ajaxSubmit(options);
}

/**
 * 格式化日期
 * @param dateStr yyyy-MM-dd HH:mm:ss格式的字符串
 * @param pattern 日期格式
 */
function fnFormatDate(dateStr, pattern) {
	if(dateStr) {
		try {
			var d = new Date(dateStr.replace(/-/g, "\/"));
			if(fnIsValidDate(d)) {
				return d.format(pattern);
			} else {
				return dateStr;
			}
		} catch(e) {
			return dateStr;
		}
	} else {
		return "";
	}
}

function fnIsValidDate(d) {
	if (Object.prototype.toString.call(d) !== "[object Date]" )
	    return false;
	return !isNaN(d.getTime());  
}

/**
 * 将回车换行符替换为<br/>符号
 * @param str
 */
function fnFormatText(str) {
	if(str) {
		return str.replace(/\r\n/gi,"<br/>").replace(/\n/gi,"<br/>");
	} else {
		return "";
	}
}

//时间格式化
Date.prototype.format = function(format){
   /*
  * eg:format="yyyy-MM-dd hh:mm:ss";
    */
   if(!format){
      format = "yyyy-MM-dd";
    }

  var o = {
           "M+": this.getMonth() + 1, // month
           "d+": this.getDate(), // day
           "h+": this.getHours(), // hour
           "H+": this.getHours(), // hour
           "m+": this.getMinutes(), // minute
           "s+": this.getSeconds(), // second
           "q+": Math.floor((this.getMonth() + 3) / 3), // quarter
            "S": this.getMilliseconds()
            // millisecond
   };

    if (/(y+)/.test(format)) {
       format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
   }

    for (var k in o) {
        if (new RegExp("(" + k + ")").test(format)) { 
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" +o[k]).length));
        }
    }
    return format;
};	

/*
函数：计算两个日期之间的差值
参数：date是日期对象
	flag：ms-毫秒，s-秒，m-分，h-小时，d-天，M-月，y-年
返回：当前日期和date两个日期相差的毫秒/秒/分/小时/天
*/
Date.prototype.dateDiff = function (date, flag) 
{
	var msCount;
	var diff = this.getTime() - date.getTime();
	switch (flag) 
	{
		case "ms":
			msCount = 1;
			break;
		case "s":
			msCount = 1000;
			break;
		case "m":
			msCount = 60 * 1000;
			break;
		case "h":
			msCount = 60 * 60 * 1000;
			break;
		case "d":
			msCount = 24 * 60 * 60 * 1000;
			break;
	}
	return Math.floor(diff / msCount);
};

/*
函数：判断一个年份是否为闰年
返回：是否为闰年
*/
Date.prototype.isLeapYear = function () {
	var year = this.getFullYear();
	return (year % 4 == 0) && (year % 100 != 0 || year % 400 == 0);
};

//附件功能
function doAttach(opts) {
	if(!opts.attachId) {opts.attachId="";}
	opts.readOnly = opts.readOnly || false;
	var attUrl = __ctx+'/sys/attach/attach.action?1=1&entityName='+opts.entityName+"&bid=" +opts.id+"&key="+opts.key
				+ "&attachId=" + opts.attachId + "&dgId=" + opts.dgId + "&flag=" + opts.flag+"&readOnly="+opts.readOnly;
	if($("#attachWin").length == 0) {
		var p =	$("<div/>").appendTo("body");
		p.window({
			id:'attachWin',
			title:$.jwpf.system.attach.attachList,
			href:attUrl,
			width:600,
			height:400,
			closable:true,
			collapsible:true,
			maximizable:true,
			minimizable:false,
			modal: true,
			shadow: false,
			cache:false,
			closed:true,
			onClose:function() {
				$("#attachWin").window("destroy");
			}
		});
	} else {
		$("#attachWin").window("refresh", attUrl);
	}
	$("#attachWin").window("open");
}	

/**
 * 启动流程
 * @param id
 * @param tName
 * @param callFunc
 */
function  doStartProcess(id,tName,callFunc,approveDesp){
	var options = {
			url :__ctx+'/gs/process!startPrepare.action',
			data : {
				"bname":tName,
				"bid":id,
				"approveDesp":approveDesp
			},
			success : function(data) {
				if (data.msg) {
					var funName = callFunc.toString().match(/function\s+([^\(]+)/)[1];//传递一个js函数的名字
						var attUrl = __ctx+"/gs/process!init.action?roles="+encodeURIComponent(data.msg) +"&bname="+tName+"&bid="+id+"&fname="+funName;
						if($("#processWin").length == 0) {
							var p =	$("<div/>").appendTo("body");
							p.window({
								id:'processWin',
								title:$.jwpf.system.process.processStartWin,
								href: attUrl,
								width:500,
								height:400,
								closable:true,
								collapsible:true,
								maximizable:true,
								minimizable:false,
								modal: true,
								shadow: false,
								cache:false,
								closed:true,
								onClose:function() {
									$("#processWin").window("destroy");
								},
								onLoad:function() {
									$("#_start_flow_approve_desp_").val(approveDesp||"");
								}
							});
						} else {
							$("#processWin").window("refresh", attUrl);
						}
						$("#processWin").window("open");
				}else{
					 $.messager.alert($.jwpf.system.alertinfo.titlet, $.jwpf.system.process.startSuccess,'info');
					 if(callFunc) { setTimeout(callFunc, 2000);}
				}				
			}
		};
	fnFormAjaxWithJson(options,true);
}

//自定义发送消息通知给选择的用户
function doSendMessageToUser(type,callFunc){
		var attUrl = __ctx+'/gs/gs-mng!selUserWin.action?type='+type;
		var p =	$("<div style='overflow: auto;'/>").appendTo("body");
		p.dialog({
			id:'sel_usersWin',
			title:'选择提醒用户',
			href:attUrl,
			width:450,
			height:350,
			closable:true,
			collapsible:true,
			maximizable:true,
			minimizable:false,
			resizable:true,
			modal: true,
			shadow: false,
			cache:false,
			closed:true,
			onClose:function() {
				$("#sel_usersWin").dialog("destroy");
			},
			buttons:[{
				text:'确定',
				iconCls:'icon-ok',
				handler:function(){
					var zTree = $.fn.zTree.getZTreeObj("m_users_");
					if(zTree!=null){
					var nodes = zTree.getCheckedNodes(true);
					var nodeIds = [];
					$.each(nodes, function(k,v) {
						nodeIds.push(v.idNum);
					});
					var userIds = nodeIds.join(",");
					if(callFunc){
						callFunc(userIds);
						$('#sel_usersWin').dialog('close');
						}
					}				
				}
			},{
				text:'取消',
				iconCls:'icon-cancel',
				handler:function(){
					$('#sel_usersWin').dialog('close');
				}
			}]
		});
	$("#sel_usersWin").dialog("open");
}
/**
 * 打开字典树窗口，进行分类选择，暂时不用
 * @param opt
 */
function doOpenDictTreeWin(opt){
		var opts = $.extend({"title":"分类选择","width":450,"height":350} ,opt);
		var attUrl = __ctx+'/sys/commmon/dict-tree.action?type='+opts.type;
		var p =	$("<div style='overflow: auto;'/>").appendTo("body");
		p.dialog({
			id:'_sel_dictTree_dialog_',
			title:opts.title,
			href:attUrl,
			width:opts.width,
			height:opts.height,
			closable:true,
			collapsible:true,
			maximizable:true,
			minimizable:false,
			resizable:true,
			modal: true,
			shadow: false,
			cache:false,
			closed:true,
			onClose:function() {
				$("#_sel_dictTree_dialog_").dialog("destroy");
			},
			buttons:[{
				text:'确定',
				iconCls:'icon-ok',
				handler:function(){
					if(callFunc){
						var node = _getCommonTypeNode_();
						var obj = {"key":node.id,"caption":node.name};
						callFunc(obj);
						$('#_sel_dictTree_dialog_').dialog('close');
					}
				}
			},{
				text:'取消',
				iconCls:'icon-cancel',
				handler:function(){
					$('#_sel_dictTree_dialog_').dialog('close');
				}
			}]
		});
		$("#_sel_dictTree_dialog_").dialog("open");
}
/*
url: 转向网页的地址
name: 网页名称，可为空
iWidth: 弹出窗口的宽度
iHeight: 弹出窗口的高度
*/
function fnOpenWindow(url,name,iWidth,iHeight){
	//获得窗口的垂直位置
	var iTop = (window.screen.availHeight-30-iHeight)/2;
	//获得窗口的水平位置
	var iLeft = (window.screen.availWidth-10-iWidth)/2;
	window.open(url,name,'height='+iHeight+',,innerHeight='+iHeight+',width='+iWidth+',innerWidth='+iWidth+',top='+iTop+',left='+iLeft+',status=yes,toolbar=no,menubar=no,location=no,resizable=yes,scrollbars=yes,titlebar=no');
}
function fnOpenWindow2(url,name){
	window.open(url,name,'status=yes,toolbar=no,menubar=no,location=no,resizable=yes,scrollbars=yes,titlebar=no,fullscreen=3');
}

/***传入相应参数(sql)，返回json结果 */
function getJsonObjByUrl(param, url) {
	var jsonData=null;
	var opt = {
			data:param,
			async:false,
            url:url,
			success:function(data){
				jsonData=data.msg;
			}
	};
	fnFormAjaxWithJson(opt, true);
	return jsonData;
}
/**
 * 批量修改拥有者
 * @param rows 选中记录数据
 * @param winId 窗口Id
 * @param entityName
 * @param callFunc
 */
function doUpdateCreateUser(rows,entityName,callFunc) {
	 var ids = [];
	 if(rows && rows.length>0){
		 for(var i =0;i<rows.length;i++){
			ids.push(rows[i].id);
		 }        		
	 }
	var edittabs = $('#_user_sel_win').find("iframe");
	var editwin = edittabs[0].contentWindow.window;
	var userId = editwin.getUserId();
	var options = {
			url : __ctx+'/gs/gs-mng!updateCreateUser.action',
			data : {
				"entityName":entityName,
				"entityIds":ids,
				"field":"createUser",
				"value":userId
			},
			success : function(data) {
				if (data.msg) {
					if(callFunc){
						callFunc();
					}
					$('#_user_sel_win').window("close");
				}
			},
			traditional:true
		};
	fnFormAjaxWithJson(options, true);
}
/**
 * 重新恢复已审批记录的流程
 * @param entityId 
 * @param entityName
 */
function doRecoverProcess(id,entityName,callFunc) {
	var options = {
			url : __ctx+'/gs/process!recoverProcess.action',
			data : {
				"entityName":entityName,
				"id":id
			},
			success : function(data) {
				if(callFunc){
					callFunc();
				}
			}
		};
	fnFormAjaxWithJson(options, true);
}

/**
 * 打开自定义选择用户窗口
 * @param url 
 * @param title
 */
function doOpenUserWin(url,title) {
	if($("#_user_sel_win").length == 0){
		var p =	$("<div/>").appendTo("body");
		var ifr = [];
		var strUrl = url;
		var imgPath = __ctx+"/themes/default/blue/images/loading.gif";
		ifr.push('<iframe src="');
		ifr.push(imgPath);
		ifr.push('" frameborder="0" style="width:100%;height:100%" ></iframe>');
		var c = ifr.join("");
		p.window({
			id:'_user_sel_win',
			title:title,
			width:400,
			height:180,
			closable:true,
			content:c,
			modal: true,
			shadow: false,
			minimizable:false,
			cache:false,
			doSize :true,
			onOpen:function(){
				var ifWin = $('#_user_sel_win').find("iframe");
				ifWin[0].contentWindow.window.location.replace(strUrl);
			},
			onClose: function(){
				var ifWin = $('#_user_sel_win').find("iframe");
				ifWin[0].contentWindow.window.location.replace(imgPath);
			}
		});
	}
	$("#_user_sel_win").window("open");
}

/**
 * 打开Excel导入窗口
 * @param url 
 * @param title
 */
function doOpenExcelImportWin(entityName,title) {
	var winTitle = title || "Excel导入";
	var strUrl = __ctx+"/gs/gs-mng!importFile.action?entityName=" + entityName;
	doOpenModuleOperWin(strUrl, winTitle, 500, 300);
}

/**
 * 获取导出参数
 * @param formKey
 * @returns
 */
function getExportParams(formKey) {
	var opt = $("#"+formKey).datagrid("options");
	var param = opt["queryParams"];
	var sort = opt["sortName"];
	var order = opt["sortOrder"];
	var queryParam = $.extend(true, {"sort":sort,"order":order}, param);
	var strParam = JSON.toUrlParam(queryParam);
	return strParam;
}

/**
 * 导出Excel格式数据文件
 * @param entityName
 * @param ids
 */
function doExportExcel(entityName, queryParams, ids, notNeedConfirm) {
	var strUrl = __ctx+"/gs/gs-mng!exportModuleExcel.action?entityName=" + entityName + "&" + queryParams + "&value=" + ids;
	if(!ids) {
		if(notNeedConfirm) {
			window.open(strUrl);
		} else {
			$.messager.confirm('提示', '您没有选择数据，确认要导出全部数据吗？', function(r) {
	            if(r) {
	            	window.open(strUrl);
	            }
			});
		}
	} else {
		window.open(strUrl);
	}
}

/**
 * 打开模块操作窗口
 * @param url
 * @param title
 * @param width
 * @param height
 * @param isMaxWin
 */
function doOpenModuleOperWin(url, title, width, height, isMaxWin) {
	var winTitle = title || "操作窗口";
	var winWid = width || 800;
	var winHei = height || 600;
	var winMax = isMaxWin || false;
	var p = $("<div/>").appendTo("body");
	var ifr = [];
	var strUrl = url;
	var imgPath = __ctx+"/themes/default/blue/images/loading.gif";
	ifr.push('<iframe src="');
	ifr.push(imgPath);
	ifr.push('" frameborder="0" style="width:100%;height:100%" ></iframe>');
	var c = ifr.join("");
	p.window({
		id:'_module_oper_win',
		title:winTitle,
		width:winWid,
		height:winHei,
		closable:true,
		content:c,
		modal: true,
		shadow: false,
		minimizable:false,
		maximized:winMax,
		cache:false,
		doSize :true,
		onOpen:function(){
			var ifWin = $('#_module_oper_win').find("iframe");
			ifWin[0].contentWindow.window.location.replace(strUrl);
		},
		onClose: function(){
			$("#_module_oper_win").window("destroy");
		}
	});		
	$("#_module_oper_win").window("open");
}
/**
 * 关闭模块操作窗口
 */
function doCloseModuleOperWin() {
	$("#_module_oper_win").window("close");
}

/**
 * 打开模块操作对话框
 * @param url
 * @param title
 * @param width
 * @param height
 * @param callFunc
 * @param isMaxWin
 */
function doOpenModuleOperDialog(url, title, width, height, callFunc, isMaxWin) {
	var winTitle = title || "操作对话框";
	var winWid = width || 800;
	var winHei = height || 600;
	var winMax = isMaxWin || false;
	var p = $("<div style='overflow: auto;'/>").appendTo("body");
	p.dialog({
		id:'_module_oper_dialog',
		title:winTitle,
		href:url,
		width:winWid,
		height:winHei,
		closable:true,
		collapsible:true,
		maximizable:true,
		minimizable:false,
		maximized:winMax,
		resizable:true,
		modal: true,
		shadow: false,
		cache:false,
		closed:true,
		onClose:function() {
			$("#_module_oper_dialog").dialog("destroy");
		},
		buttons:[{
			text:'确定',
			iconCls:'icon-ok',
			handler:function(){
				if(callFunc) {
					callFunc();
				}
			}
		},{
			text:'取消',
			iconCls:'icon-cancel',
			handler:function(){
				doCloseModuleOperDialog();
			}
		}]
	});
	$("#_module_oper_dialog").dialog("open");
}

/**
 * 关闭模块操作对话框
 */
function doCloseModuleOperDialog() {
	$("#_module_oper_dialog").dialog("close");
}

/**
 * 打开产品选型窗口
 * @param callFunc
 */
function doOpenProductSelWin(param, callFunc){
	var fp = JSON.stringify(param);
	var attUrl = "/sys/project/kbt/dataselect.action?filterParam=" + encodeURIComponent(fp);
	window.top.openFormWin({
		title:"产品选型",
		url:attUrl,
		width:1000,
		height:600,
		onAfterSure:function(win) {
			var rowData= win._getSelectProductInfo_();
			if(rowData) {
				if(callFunc){
					callFunc(rowData);
				}
				return true;
			}
		}
	});
	/*var func = function() {
		var rowData= window.top._getSelectProductInfo_();
		if(rowData) {
			if(callFunc){
				callFunc(rowData);
			}
			window.top.doCloseModuleOperDialog();
		}
	};
	window.top.doOpenModuleOperDialog(attUrl, "产品选型", 1000, 650, func);*/
}

/**
 * 打开产品信息生成窗口
 * @param callFunc
 */
function doOpenProductGenWin(xhid, callFunc){
	var attUrl = "/sys/project/kbt/product-gen.action?xhid=" + xhid;
	window.top.openFormWin({
		title:"产品信息生成向导",
		url:attUrl,
		width:850,
		height:600,
		onAfterSure:function(win) {
			var result= win._saveProductInfo_();
			if(result) {
				if(callFunc){
					callFunc();
				}
				return true;
			}
		}
	});
	/*var func = function() {
		var result = window.top._saveProductInfo_();
		if(result) {
			if(callFunc) {
				callFunc();
			}
			window.top.doCloseModuleOperDialog();
		}
	};
	window.top.doOpenModuleOperDialog(attUrl, "产品信息生成向导", 850, 600, func);*/
}

//打开组织树
function doOpenOrganizationSelWin(callFunc){
		var orgUrl = __ctx+'/sys/common/organization-ztree.action';		
		var p =	$("<div style='overflow: auto;'/>").appendTo("body");
		p.dialog({
			id:'sel_orgWin',
			title:'选择组织',
			href:orgUrl,
			width:450,
			height:350,
			closable:true,
			collapsible:true,
			maximizable:true,
			minimizable:false,
			resizable:true,
			modal: true,
			shadow: false,
			cache:false,
			closed:true,
			onClose:function() {
				$("#sel_orgWin").dialog("destroy");
			},
			buttons:[{
				text:'确定',
				iconCls:'icon-ok',
				handler:function(){
					var zTree = $.fn.zTree.getZTreeObj("m_org_");
					if(zTree!=null){
					var nodes = zTree.getCheckedNodes(true);
					var nodeIds = [];
					$.each(nodes, function(k,v) {
						nodeIds.push(v.id);
					});
					var orgIds = nodeIds.join(",");
					if(callFunc){
						callFunc(orgIds);
						$('#sel_orgWin').dialog('close');
						}
					}				
				}
			},{
				text:'取消',
				iconCls:'icon-cancel',
				handler:function(){
					$('#sel_orgWin').dialog('close');
				}
			}]
		});
	$("#sel_orgWin").dialog("open");
}
/**
 * 打开自定义表单窗口
 * @param fromParam
 * 包含以下参数
 * formName
 * formKey
 * onAfterSure
 * width
 * height
 * isMaxWin
 * filterParam
 * id
 */
function openFormWin(formParam){
	var defaultParam = {
			"title":"操作对话框",
			"width":800,
			"height":600,
			"filterParam":{},
			"addParam":{},//新增参数
			"urlParam":null,//附加参数
			"isMaxWin":false,
			"isModal":true,//模式窗口
			"showTools":true,//显示按钮栏
			"onAfterSure":null};
	var param = $.extend(defaultParam, formParam);
	var fp = JSON.stringify(param.filterParam);
	var formKey = (param.formKey)?param.formKey.toLowerCase():"";
	var url = __ctx+"/gs/forms/"+formKey+".action?queryParams="+(encodeURIComponent(fp)||"").replace(/\'/,"%27");
	if(param.url) {
		url = __ctx+param.url;
	}
	if(param.id) {
		url += "&id=" + param.id;
	}
	if(param.addParam) {
		url += "&addParams=" + encodeURIComponent(JSON.stringify(param.addParam));
	}
	if(param.urlParam) {
		url += param.urlParam;
	}
	var win = "<iframe id='_form_win_ifr'  src='"+ url +"' frameborder='0' style='width:100%;height:100%' scrolling='auto'></iframe>";
	var winTitle = param.title;
	var winWid = param.width;
	var winHei = param.height;
	var winMax = param.isMaxWin;
	var isModal = param.isModal;
	var callFunc = param.onAfterSure;
	var p = $("<div style='overflow: hidden;'/>").appendTo("body");
	var opt = {
			id:'_form_win_',
			title:winTitle,
			content: win,
			width:winWid,
			height:winHei,
			closable:true,
			collapsible:true,
			maximizable:true,
			minimizable:false,
			maximized:winMax,
			resizable:true,
			modal: isModal,
			shadow: false,
			cache:false,
			closed:true,
			onClose:function() {
				$("#_form_win_").dialog("destroy");
			}
	};
	if(param.showTools) {
		opt["buttons"] = [{
			text:'确定',
			iconCls:'icon-ok',
			handler:function(){
				if(callFunc) {
					var wins = $('#_form_win_').find("iframe");
					var win = wins[0].contentWindow.window;
					var result = callFunc(win);
					if(result) $("#_form_win_").dialog("close");
				}
			}
		},{
			text:'取消',
			iconCls:'icon-cancel',
			handler:function(){
				$("#_form_win_").dialog("close");
			}
		}];
	}
	if($('#_form_win_').length) {
		alert("操作对话框已经打开，请先关闭打开的对话框再操作！");
		return;
	}
	p.dialog(opt);
	$("#_form_win_").dialog("open");
}

/**
 * 打开自定义表单窗口 layui方式打开弹窗
 * @param fromParam
 * 包含以下参数
 * formName
 * formKey
 * onAfterSure
 * width
 * height
 * isMaxWin
 * filterParam
 * id
 */
function openFormWinV2(formParam){
	var defaultParam = {
			"winId":"",//窗口ID
			"title":"操作",
			"width":800,
			"height":400,
			"url":null,
			"size":"large",//尺寸大小
			"message":"",//窗口内容
			"isIframe":true,
			"isExtUrl":false,//外部链接
			"isTop":false,
			"filterParam":{},
			"addParam":{},//新增参数
			"urlParam":null,//附加参数
			"isMaxWin":false,
			"zIndex":1024,//层叠顺序
			"isModal":true,//模式窗口
			//"isUseLayui":false,//是否启用layui--layer
			"showTools":true,//显示按钮栏
			"onAfterSure":null//确认按钮
			,"onAfterCancel":null
			,"okTitle":"确认"
			,"cancelTitle":"取消"
			,"onInit":null//初始化事件
			,"onHide":null//窗口关闭后事件
	};
	var param = $.extend(defaultParam, formParam);
	var fp = JSON.stringify(param.filterParam);
	var formKey = (param.formKey)?param.formKey.toLowerCase():"";
	var winId = "_form_win_ifr_" + (param.winId || "");
	var url = __ctx+"/gs/forms/"+formKey+".action?queryParams="+(encodeURIComponent(fp)||"").replace(/\'/g,"%27");
	if(param.url) {
		url = (param.isExtUrl ? "": __ctx)+param.url;
	}
	if(url.indexOf("?") < 0) {
		url += "?1=1";
	}
	if(param.id) {
		url += "&id=" + param.id;
	}
	if(param.addParam) {
		url += "&addParams=" + encodeURIComponent(JSON.stringify(param.addParam));
	}
	if(param.urlParam) {
		url += param.urlParam;
	}
	var winHei = param.height || "100%";
	if($.isNumeric(winHei)) {
		winHei = winHei + "px";
	}
	var winWid = param.width || "100%";
	if($.isNumeric(winWid)) {
		winWid = winWid + "px";
	}
	var win = "";
	var isIframe = param.isIframe;
	if(isIframe) {
	   win = "<iframe id='" + winId + "'  src='"+ url +"' frameborder='0' style='width:100%;height:"+winHei+"'></iframe>";
	} else {
	   win = (typeof param.message=='string')?"<div id='"+winId+"' style='width:100%;height:" + winHei + "'>"+param.message+"</div>":param.message;
	}
	var winTitle = param.title;
	var winMax = param.isMaxWin;
	var isModal = param.isModal;
	var callFunc = param.onAfterSure;
	var cancelFunc = param.onAfterCancel;
	var thisWin = top;
	if (!param.isTop) {
		thisWin = self;
	}
		var opt = {
			type: isIframe?2:1,
			title: winTitle,
			shadeClose:!isModal,
			content: isIframe?url:win,
			area:[winWid, winHei],
			maxmin:true,
			zIndex:param.zIndex || 1024,
			success: function(layero, index){
				if(!isIframe && !param.message) {
					$(layero).find("#"+winId).load(url);
				}
				if(param.onInit) {
					param.onInit.call(layero, index);
				}
			},
			end: function() {
				if(param.onHide) {
					param.onHide.call(this);
				}
			}
		};
		if(param.showTools) {
			var btOpt = {
				btn: [param.okTitle, param.cancelTitle]
				,yes: function(index, layero){
					var result = null;
					if (callFunc) {
						var win = thisWin;
						if (isIframe) {
							var wins = $(layero).find("iframe");
							win = wins[0].contentWindow.window;
						}
						result = callFunc(win);
					}
					result !== false && layer.close(index);
				}
				,btn2: function(index, layero){
					var result = null;
					if (cancelFunc) {
						var win = thisWin;
						if (isIframe) {
							var wins = $(layero).find("iframe");
							win = wins[0].contentWindow.window;
						}
						result = cancelFunc(win);
					}
					result !== false && layer.close(index);
				}
			};
			$.extend(true, opt, btOpt);
		}
		layer.open(opt);
}

$(document).keydown(function(e){ 
    var keyEvent; 
    if(e.keyCode==8){ 
        var d=e.srcElement||e.target; 
        if(d.tagName.toUpperCase()=='INPUT'||d.tagName.toUpperCase()=='TEXTAREA'){ 
            keyEvent=d.readOnly||d.disabled; 
        }else{ 
            keyEvent=true; 
        } 
    }else{ 
        keyEvent=false; 
    } 
    if(keyEvent){ 
        e.preventDefault(); 
    } 
}); 


var $MsgUtil = {
		alert:function(opt, method) {
			var op = method || "warning";
			top.toastr.options = {
				"closeButton":true,
				"positionClass": "toast-top-center"
			}
			top.toastr[op](opt);
		},
		info:function(opt) {
			$MsgUtil.alert(opt, "info");
		}
};

window.alert = function(msg) {
	$MsgUtil.alert(msg);
};

var pageStorage = {
		name: 'pageStorage',
		storage: {},
		read: function(key) { 
			return this.storage[key];
		},
		write: function(key, value) {
			this.storage[key] = value;
		},
		each: function(callback) {
			var memoryStorage = this.storage;
			for (var key in memoryStorage) {
				if (memoryStorage.hasOwnProperty(key)) {
					callback(memoryStorage[key], key);
				}
			}
		},
		remove: function(key) {
			delete this.storage[key];
		},
		clearAll: function() {
			this.storage = {};
		}
};
	
window.PageStorage = pageStorage;